
//
//  WZEmojiManager.swift
//  weibo
//
//  Created by mac on 16/3/7.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class WZEmojiManager: NSObject {
    
    static var recentEmotions: [WZEmojiModel] = [WZEmojiModel]()
//    MARK:定义4个表情包
    static var defaltEmotions: [WZEmojiModel] = {
      return  WZEmojiManager.readEmoji("com.sina.default")
    
    }()
    static var emojiEmotions: [WZEmojiModel] = {
        return WZEmojiManager.readEmoji("com.apple.emoji")
    }()
    
    static var xlhEmotions: [WZEmojiModel] = {
        return WZEmojiManager.readEmoji("com.sina.lxh")
    }()
    
    //    MARK:实现一个类方法获取所有表情并且是3维数组
    class func getAllEmotions()->[[[WZEmojiModel]]]{
        return [
            pageEmotions(recentEmotions),
            pageEmotions(defaltEmotions),
            pageEmotions(emojiEmotions),
            pageEmotions(xlhEmotions)]
    }
    
    //    MARK:实现一个类方法获取表情数组
    class func readEmoji(packageName:String)->[WZEmojiModel]{
        let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
        let packagePath = (bundlePath! as NSString).stringByAppendingPathComponent(packageName)
        let infoPath = (packagePath as NSString).stringByAppendingPathComponent("info.plist")
        let dict = NSDictionary(contentsOfFile: infoPath)
        
        let array = dict!["emoticons"] as! [[String :NSObject]]
        var result = [WZEmojiModel]()
        for emoji in array{
            let emojiModel = WZEmojiModel(dict: emoji)
            emojiModel.path = packagePath
            
            result.append(emojiModel)
        }
        return result
  
        
    }
    
    class func pageEmotions(emotions: [WZEmojiModel])->[[WZEmojiModel]]{
        
        let page = (emotions.count - 1) / 20 + 1
        
         var result = [[WZEmojiModel]]()
        
        for i in 0..<page{
            
            var lenth = 20
            
            if i == page - 1{
                lenth =  emotions.count - i * 20
            }
            
            let array = (emotions as NSArray).subarrayWithRange(NSMakeRange(20 * i, lenth)) as! [WZEmojiModel]
            
            result.append(array)
        }
        return result
    }
    
   class func addRecentEmotion(emotion:WZEmojiModel?){
        
        if let Oemotion = emotion{
            
            if !recentEmotions.contains(Oemotion){
                recentEmotions.insert(Oemotion, atIndex: 0)
                
            }
            
            if recentEmotions.count > 20{
                recentEmotions.removeAtIndex(20)
            }
            
        }
        
    }
    
    
}
